package ar.edu.itba.it.pdc.proxy.filters;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

import ar.edu.itba.it.pdc.app.Madonna3;
import ar.edu.itba.it.pdc.app.config.mapping.Filter;
import ar.edu.itba.it.pdc.protocol.email.Mail;
import ar.edu.itba.it.pdc.utils.TempFilesSetup;

public class FilterRunner {
	
	private final static String CRLF = TempFilesSetup.CRLF;

	public static void run(Mail mail) {
		for (Filter f : Madonna3.getApp().getSettings().getProxy().getFilters().getFilter()) {
			if (f.getStatus() == 1) {
				Madonna3.log.info("Applying filter: " + f.getCommand());
				runFilter(f.getCommand(), mail);
			}
		}
	}

	private static void runFilter(String command, Mail mail) {
		try {
			Process p = Runtime.getRuntime().exec(command);
			String aux;
			
			BufferedWriter inputP = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
			
			inputP.write(mail.getUnfoldedHeaders() + CRLF);
			
			BufferedReader reader = mail.getBody();
			while((aux = reader.readLine()) != null) {
				inputP.write(aux + CRLF);
			}
			inputP.close();
			
			Mail result = Mail.build(p.getInputStream());
			mail.replaceWith(result);

		} catch (Exception e) {
			Madonna3.log.error("Can't apply filter");
		}
	}
}
